/*
 * dmBridge: a data access framework for CONTENTdm(R)
 *
 * Copyright © 2009, 2010, 2011 Board of Regents of the Nevada System of Higher
 * Education, on behalf of the University of Nevada, Las Vegas
 */

/**
 * Encapsulates an RFC 2396 Uniform Resource Identifier (URI), a superset
 * of a URL.
 *
 * @author Alex Dolski <alex.dolski@unlv.edu>
 * @license http://www.opensource.org/licenses/mit-license.php
 */

/**
 * @param str Absolute URI or URI path
 */
function URI(str) {
	this.host = null;
	this.path = null;
	this.port = 80;
	this.scheme = "http";
	this.queryKeys = [];
	this.queryValues = [];
	this.validationErrors = [];

	this.setString(str);
}

URI.prototype.unsetQuery = function() {
	this.queryKeys = [];
	this.queryValues = [];
}

/**
 * @param key
 */
URI.prototype.unsetQueryValuesForKey = function(key) {
	for (var i = this.queryKeys.length; i >= 0; i--) {
		if (this.queryKeys[i] == key) {
			this.queryKeys.splice(i, 1);
			this.queryValues.splice(i, 1);
		}
	}
}

/**
 * @param key
 */
URI.prototype.getQueryValuesForKey = function(key) {
	var values = [];
	for (var i = 0; i < this.queryKeys.length; i++) {
		if (this.queryKeys[i] == key) {
			values.push(this.queryValues[i]);
		}
	}
	return values;
}

/**
 * @return string String representation of the absolute URI path
 */
URI.prototype.toAbsolutePath = function() {
	var str = "";
	if (this.path.length > 0) {
		str += this.path;
	}
	if (this.queryKeys.length > 0) {
		var pairs = [];
		for (var i = 0; i < this.queryKeys.length; i++) {
			pairs[i] = this.queryKeys[i] + "=" + this.queryValues[i];
		}
		str += "?" + pairs.join("&");
	}
	return str;
}

/**
 * @return string String representation of the absolute URI
 */
URI.prototype.toAbsoluteString = function() {
	var str = this.scheme + "://" + this.host;
	if (this.port != 80) {
		str += ":" + this.port;
	}
	return str + this.toAbsolutePath();
}

/**
 * @param str String representation of the absolute URI or URI path
 * @return boolean
 */
URI.prototype.setString = function(str) {
	this.validationErrors = [];

	// scheme
	var tmp = str.split(":");
	if (tmp[0] == "http" || tmp[0] == "https") {
		// it's an absolute URI
		this.scheme = tmp[0];
		// host/port
		this.host = tmp[1].split("/")[2];
		this.port = tmp[2].split("/")[0];
		// path
		this.path = tmp[2].split("/")[1].spit("?")[0];
	} else {
		// path
		this.path = str.split("?")[0];
	}

	// query
	var parts = str.split("?");
	if (parts.length < 2) {
		this.validationErrors.push("Missing query string.");
		return false;
	}
	var pairs = parts[1].split("&");
	for (var i = 0; i < pairs.length; i++) {
		var pair = pairs[i].split("=");
		this.queryKeys[i] = pair[0];
		this.queryValues[i] = pair[1];
	}

	return true;
}
